package com.itbaizhan.service.impl;

import com.itbaizhan.dao.CommentDao;
import com.itbaizhan.dao.OrderDao;
import com.itbaizhan.exception.BusException;
import com.itbaizhan.pojo.Comment;
import com.itbaizhan.pojo.Order;
import com.itbaizhan.result.CodeEnum;
import com.itbaizhan.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author spf
 * @date 2024/3/4
 * @time 19:33
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentDao commentDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    public void saveComment(String orderId, Comment comment) {
        try{
//            Order order = orderDao.finById(orderId);
            Order order = new Order();
            order.setItemId("65e57cd895c7f93af5028c27");
            order.setUsername("18834388781");
            comment.setUsername(order.getUsername());
            comment.setItemId(order.getItemId());

            commentDao.save(comment);

            orderDao.updateCommentState(orderId, 2);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusException(CodeEnum.SAVE_COMMENT_ERROR);
        }
    }

    @Override
    public List<Comment> findByPage(String itemId, int page, int rows) {
        Query query = new Query();
        query.addCriteria(Criteria.where("itemId").is(itemId));
        query.with(PageRequest.of(page, rows));

        List<Comment> commentByPage = commentDao.findCommentByPage(query);

        // 隐藏用户名
        for (Comment comment : commentByPage) {
            String username = comment.getUsername().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            comment.setUsername(username);
        }
        return commentByPage;
    }
}
